<template>
  <div ref="chinaMap" class="chinaMap"></div>
</template>

<script setup>
import { nextTick, watch } from "vue";
import * as echarts from "echarts";
import suzhou from "@/assets/suzhou.json";
import suzhouLine from "@/assets/suzhouline.json";
import { onMounted, onBeforeUnmount, ref } from "vue";
import { fontSize } from "@/utils/px2rem.js";

const props = defineProps({
  data: {
    type: Array,
    default: () => [],
  },
});
//设置投射点
const scatterPos = [120.41453, 31.342948];

const numberbgurl =
  "image://" + new URL(`@/assets/image/posture/numberbg.png`, import.meta.url);
const chinaMap = ref(null);

const zoomLevel = ref(1);
zoomLevel.value = sizeCal();

let resizeObserver;
let myChart = null;
let series = [];
let showData = [];
let chinaDatas = [];
let popupData = [];
let chinaGeoCoordMap = {};
suzhou.features.map((item) => {
    chinaGeoCoordMap[item.properties.name] = item.properties.center;
})
function handleData(data) {
  data.forEach((item) => {
    const prop = item.szsdq.replace("苏州市", "");
    chinaDatas.push([{ name: prop }]);
    popupData.push({
      name: prop,
      value: chinaGeoCoordMap[prop],
      count: item.rs,
    });
  });
  [["虎丘区", chinaDatas]].forEach((item) => {
    series.push(
      //设置指向箭头信息
      {
        type: "lines",
        zlevel: 6,
        effect: {
          show: true,
          period: 2, //箭头指向速度，值越小速度越快
          trailLength: 0.04, //特效尾迹长度[0,1]值越大，尾迹越长重
          symbol: "pin", //箭头图标
          symbolSize: 6, //图标大小
          color: "#ffe4a9",
        },

        lineStyle: {
          normal: {
            color: "#ff8121",
            width: 1, //尾迹线条宽度
            opacity: 0.4, //尾迹线条透明度
            curveness: 0.3, //尾迹线条曲直度
          },
        },
        data: convertData(item[1]),
      },

      {
        type: "scatter",
        coordinateSystem: "geo",
        zlevel: 2,
        label: {
          normal: {
            show: true,
            position: "bottom",
            formatter: "{b}",
            textStyle: {
              color: "#fff",
              fontSize: 12,
            },
          },
        },
        symbol: "image://image/marker.png",
        symbolSize: 30,
        data: [
          {
            value: scatterPos,
          },
        ],
      }
    );
  });
  nextTick(() => {
    initMap();
  });
}

let index = 0;
showData = [popupData[index]];
let timer = setInterval(() => {
  index++;
  showData = [popupData[index]];
  if (index === popupData.length) {
    index = 0;
  }
  resizeMap();
 
}, 3000);

watch(
  () => props.data,
  (newVal) => {
    chinaDatas = [];
    popupData = [];
    series = [];
    handleData(newVal);
  },{
  immediate: true
});


function sizeCal() {
  const windowWidth = window.innerWidth;
  const pixelRatio =
    window.devicePixelRatio > 1
      ? window.devicePixelRatio - 1
      : window.devicePixelRatio;
  return (windowWidth / 1920) * (1.15 - pixelRatio * 0.25);
}



function convertData(data) {
  var res = [];
  for (var i = 0; i < data.length; i++) {
    var dataItem = data[i];
    var fromCoord = scatterPos;
    var toCoord = chinaGeoCoordMap[dataItem[0].name];
    if (fromCoord && toCoord) {
      res.push([
        {
          coord: fromCoord,
          value: dataItem[0].value,
        },
        {
          coord: toCoord,
        },
      ]);
    }
  }
  return res;
}

const resizeHandler = throttle(resizeMap, 100);
onMounted(() => {
  resizeObserver = new ResizeObserver(resizeHandler);
  if (chinaMap.value) {
    resizeObserver.observe(chinaMap.value);
  }
});



function initMap() {
  myChart = echarts.init(chinaMap.value);
  echarts.registerMap("suzhouLine", suzhouLine);
  echarts.registerMap("suzhou", suzhou);
  drawMap();
}

function drawMap() {
  const colors = [
    "#FF1493",
    "#FF69B4",
    "#df9dd0",
    "#7B68EE",
    "#1E90FF",
    "#87CEFA",
    "#4169E1",
  ];
  const option = {
    geo: [
      {
        map: "suzhouLine",
        show: true,
        roam: false,
        zlevel: 4,
        zoom: zoomLevel.value,
        aspectScale: 0.8,
        layoutCenter: ["50%", "44%"],
        layoutSize: 600,
        boxDepth: 10,
        z: 1,
        itemStyle: {
          areaColor: "transparent",
          borderColor: "#8ABEFF",
          borderWidth: 3,
        },
        silent: true,
      },
      {
        map: "suzhouLine",
        show: true,
        roam: false,
        zlevel: 3,
        zoom: zoomLevel.value - 0.03,
        aspectScale: 0.82,
        layoutCenter: ["50%", "44%"],
        layoutSize: 600,
        boxDepth: 10,
        z: 1,
        itemStyle: {
          areaColor: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [
              {
                offset: 0,
                color: "rgba(13, 131, 204,1)",
              },
              {
                offset: 1,
                color: "rgba(22, 86, 181,1)",
              },
            ],
            global: false,
          },
          shadowColor: "#074095",
          shadowOffsetX: -5,
          shadowOffsetY: -12,
          shadowBlur: 1,
          borderColor: "transparent",
        },
        silent: true,
      },
      {
        map: "suzhouLine",
        show: true,
        roam: false,
        zlevel: 2,
        zoom: zoomLevel.value,
        aspectScale: 0.8,
        layoutCenter: ["50%", "45.5%"],
        layoutSize: 600,
        boxDepth: 10,
        z: 1,
        itemStyle: {
          areaColor: "#052567",
          borderColor: "transparent",
        },
        silent: true,
      },

      {
        map: "suzhouLine",
        show: true,
        roam: false,
        zlevel: -2,
        zoom: zoomLevel.value,
        aspectScale: 0.8,
        layoutCenter: ["50%", "47%"],
        layoutSize: 600,
        boxDepth: 10,
        z: 1,
        itemStyle: {
          areaColor: "transparent",
          borderColor: "rgba(72, 163, 255,0.2)",
          borderWidth: 2,
        },
        silent: true,
      },
      {
        map: "suzhouLine",
        show: true,
        roam: false,
        zoom: zoomLevel.value,
        aspectScale: 0.8,
        zlevel: -3,
        layoutCenter: ["50%", "48%"],
        layoutSize: 600,
        boxDepth: 10,

        z: 1,
        itemStyle: {
          areaColor: "transparent",
          borderColor: "rgba(0, 207, 241, 0.2)",
          borderWidth: 2,
        },
        silent: true,
      },
    ],
    series: [
      {
        type: "map",
        map: "suzhou",
        boxDepth: 10,
        roam: false,
        layoutCenter: ["50%", "44%"],
        layoutSize: 600,
        zoom: zoomLevel.value,
        zlevel: 5,
        aspectScale: 0.8,
        showLegendSymbol: false,
        label: {
          normal: {
            show: true,
            textStyle: {
              color: "white",
              fontSize: fontSize(14),
              textShadowColor: "rgba(0, 0, 0, 0.3)",
              textShadowBlur: 4,
            },
          },
          emphasis: {
            textStyle: {
              color: "white",
            },
          },
        },
        itemStyle: {
          normal: {
            areaColor: "transparent",
            borderColor: "rgba(158,176,255,0.3)",
            borderWidth: 1,
          },
          emphasis: {
            color: "green",
            areaColor: "#17008d",
            borderWidth: 0,
          },
        },
        data: popupData
          .sort((a, b) => b.count - a.count)
          .map((item, i) => {
            return {
              name: item.name,
              itemStyle: {
                normal: {
                  areaColor: item.name === "虎丘区" ? "#FFD565" : colors[i],
                },
              },
            };
          }),
      },
      {
        name: "点",
        type: "scatter",
        coordinateSystem: "geo",
        symbol: numberbgurl,
        symbolSize:[fontSize(180), fontSize(87)],
        label: {
          normal: {
            show: true,
            formatter (params) {
              console.log(`output->params`,params)
              const item = props.data.find(
                (item) => item.szsdq.indexOf(params.name) > -1
              );
              return `{a|${params.name}}\n{b|当事人次：}{c|${item.rs}} {b|次}`;
            },
            rich: {
              a: {
                color: "#fff",
                fontSize: fontSize(14),
                fontWeight: "bold",
                height: fontSize(22),
              },
              c: {
                color: "#FFD565",
                fontSize: fontSize(14),
                fontWeight: "bold",
                height: fontSize(22),
              },
              b: {
                color: "#fff",
                fontSize: fontSize(14),
                height: fontSize(20),
              },
            },
            textStyle: {
              color: "#fff",
              fontSize: fontSize(14),
            },
          },
        },
        itemStyle: {},
        zlevel: 16,
        data: showData,
      },
      ...series,
    ],
  };
  myChart.setOption(option);
}



function resizeMap() {
  if (myChart) {
    zoomLevel.value = sizeCal();
    drawMap();
    myChart.resize();
  }
}

function throttle(func, wait) {
  let previous = 0;
  return function () {
    let now = Date.now();
    if (now - previous > wait) {
      func.apply(this, arguments);
      previous = now;
    }
  };
}
onBeforeUnmount(() => {
  if (myChart !== null) {
    myChart.dispose();
  }
  if (resizeObserver) {
    resizeObserver.unobserve(chinaMap.value);
    resizeObserver.disconnect();
  }
  if(timer){
    clearInterval(timer);
  }
});
</script>

<style scoped>
.chinaMap {
  width: 100%;
  height: 100%;
}
</style>
